package db

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"pan/db/mysql"
)

// OnFileUploadFinished: 上传完成保存文件meta信息到文件表
func OnFileUploadFinished(fileHash, fileName, fileAddr string, fileSize int64) bool {
	sql := `REPLACE INTO file
	(file_hash,
	file_name,
	file_size,
	file_addr,
	file_status)
	VALUES
	(?,
	?,
	?,
	?,
	1);`
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		fmt.Printf("prepare insert sql fail err:%s\n", err.Error())
		return false
	}
	defer stmt.Close()
	ret, err := stmt.Exec(fileHash, fileName, fileSize, fileAddr)
	if err != nil {
		fmt.Printf("excute insert sql fail err:%s\n", err.Error())
		return false
	}
	rows, err := ret.RowsAffected()
	if err == nil {
		if rows <= 0 {
			fmt.Printf("file:%s has been uploaded\n", fileHash)
		}
		return true
	}
	return false
}

type TableFile struct {
	FileHash string
	FileName sql.NullString
	FileSize sql.NullInt64
	FileAddr sql.NullString
}

// GetFileMeta: 从mysql中查询文件元信息
func GetFileMeta(filehash string) (*TableFile, error) {
	sql := `
		SELECT file_hash, file_name, file_addr, file_size
		FROM file
		WHERE file_status = 1
		AND file_hash = ?
		LIMIT 1
	`
	stmt, err := mysql.DBConn().Prepare(sql)
	if err != nil {
		return nil, err
	}
	defer stmt.Close()
	file := TableFile{}
	err = stmt.QueryRow(filehash).Scan(&file.FileHash, &file.FileName, &file.FileAddr, &file.FileSize)
	if err != nil {
		return nil, err
	}
	return &file, nil
}

// UpdateFileLocation: 更新文件地址
func UpdateFileLocation(filehash, location string) bool {
	json.Marshal([]interface{}{filehash, location})
	// res, err := execAction("/file/UpdateFileLocation", uInfo)
	return true
	// return parseBody(res), err
}
